package com.youlai.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youlai.system.mapper.EmployMapper;
import com.youlai.system.model.entity.Attendancerecord;
import com.youlai.system.mapper.AttendancerecordMapper;
import com.youlai.system.model.entity.Employ;
import com.youlai.system.model.form.AttendUpdateStatusForm;
import com.youlai.system.model.query.AttendanceQuery;
import com.youlai.system.model.vo.AttendanceRecordVO;
import com.youlai.system.service.IAttendancerecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhi1
 * @since 2024-05-28
 */
@Service
@Data
public class AttendancerecordServiceImpl extends ServiceImpl<AttendancerecordMapper, Attendancerecord> implements IAttendancerecordService {
    @Autowired
    private final EmployMapper employMapper;
    @Autowired
    private final AttendancerecordMapper attendancerecordMapper;


    @Override
    public PageInfo<AttendanceRecordVO> getAttendPage(AttendanceQuery attendanceQuery) {
        PageHelper.startPage(attendanceQuery.getPageNum(), attendanceQuery.getPageSize());

        List<AttendanceRecordVO> attendanceRecordVOList = new ArrayList<>();

        List<Employ> employs = employMapper.findAll(attendanceQuery.getDepartmentId());
        System.out.println(employs);
        for (Employ employ : employs) {
            AttendanceRecordVO attendanceRecordVO = new AttendanceRecordVO();
            attendanceRecordVO.setDepartmentId(String.valueOf(employ.getDepartmentId()));
            attendanceRecordVO.setUsername(employ.getUsername());
            attendanceRecordVO.setWorkNumber(employ.getWorkNumber());
            attendanceRecordVO.setMobile(employ.getMobile());
            attendanceRecordVO.setDepartment(employ.getDepartmentName());
            attendanceRecordVO.setUserId(employ.getId());
            System.out.println(attendanceRecordVO);


            //如果超过今天还未签到就自动插入旷工
            //获取当然得年月日，组合成day
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            int year = calendar.get(Calendar.YEAR); //2024
            int month = calendar.get(Calendar.MONTH) + 1; // 月份从 0 开始计数，所以要加 1
            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // 获取当前月的第几天

            String formattedMonth = (month < 10) ? "0" + month : String.valueOf(month);
            String formattedDayOfMonth = (daysInMonth < 10) ? "0" + daysInMonth : String.valueOf(daysInMonth);
            String formattedTodayOfMonth = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth);
            int datate = year * 10000 + Integer.parseInt(formattedMonth) * 100 + Integer.parseInt(formattedDayOfMonth);//这个月的总天数
            int today = year * 10000 + Integer.parseInt(formattedMonth) * 100 + Integer.parseInt(formattedTodayOfMonth);//这个月的当天
            int thrMonth = year * 10000 + Integer.parseInt(formattedMonth) * 100 + 01; //这个月的第一天
            System.out.println(today);
            List<Attendancerecord> attendancerecordTodayList = attendancerecordMapper.selectTodayList(today);

            QueryWrapper<Attendancerecord> queryWrapper = new QueryWrapper<Attendancerecord>()
                    .select("department_id", "user_id", "adt_statu", "adt_in_time", "adt_out_time", "day", "adt_in_place", "adt_out_place", "update_time", "update_person", "remarks")
                    .eq("user_id", employ.getId())
                    .between("day",thrMonth,datate);
            if (attendanceQuery.getDepartmentId() != null) {
                queryWrapper.eq("department_id", attendanceQuery.getDepartmentId());
            }
            if (attendanceQuery.getAdtStatu() != null) {
                queryWrapper.eq("adt_statu", attendanceQuery.getAdtStatu());
            }
            List<Attendancerecord> attendancerecords = this.list(queryWrapper);
            attendanceRecordVO.setAttendancerecordList(attendancerecords);

            List<Attendancerecord> recordsToUpdate = new ArrayList<>();
            for (Attendancerecord attendancerecord : attendancerecordTodayList) {

                if (attendancerecord.getAdtStatu() == null) {//还未签到的员工将会自动设置旷工
                    // 获取今日日期是星期几
                    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                    if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {// 判断该日期是否为周六或周日
                        attendancerecord.setAdtStatu(0);
                        attendancerecord.setUserId(attendancerecord.getUserId());
                        //自动添加休息日
                        System.out.println(attendancerecord);
                        recordsToUpdate.add(attendancerecord);
                    }
                    attendancerecord.getUserId();
                    attendancerecord.setAdtStatu(2);
                    //自动添加旷工
                    System.out.println(attendancerecord);
                    System.out.println(today);
                    recordsToUpdate.add(attendancerecord);
                }
            }
            //             执行批量更新操作
//             检查是否有数据需要更新
            System.out.println(recordsToUpdate);
            if (!recordsToUpdate.isEmpty()) {
                // 执行批量更新操作
                System.out.println(recordsToUpdate);
                attendancerecordMapper.batchUpdate(recordsToUpdate, today);
            } else {
                System.out.println("没有需要更新的记录。");
            }
            attendanceRecordVOList.add(attendanceRecordVO); // 将每个AttendanceRecordVO对象添加到列表中
        }


        System.out.println(attendanceRecordVOList);
        PageInfo<AttendanceRecordVO> pageInfo = new PageInfo(attendanceRecordVOList);
        return pageInfo;

    }

    @Override
    public Integer updateAttendUpdateStatus(AttendUpdateStatusForm attendUpdateStatusForm) {
        Attendancerecord attendancerecord = new Attendancerecord();
        BeanUtil.copyProperties(attendUpdateStatusForm, attendancerecord);
        boolean result = attendancerecordMapper.updateStatusByUserIdAndDay(attendancerecord);
        Assert.isTrue(result,"员工考勤修改失败");
        return attendancerecord.getId();

    }

    @Override
    public List<AttendanceRecordVO> getList() {
        List<AttendanceRecordVO> attendanceRecordVOList = new ArrayList<>();

        List<Employ> employs = employMapper.findAll(null);
        for (Employ employ : employs) {
            AttendanceRecordVO attendanceRecordVO = new AttendanceRecordVO();
            attendanceRecordVO.setDepartmentId(String.valueOf(employ.getDepartmentId()));
            attendanceRecordVO.setUsername(employ.getUsername());
            attendanceRecordVO.setWorkNumber(employ.getWorkNumber());
            attendanceRecordVO.setMobile(employ.getMobile());
            attendanceRecordVO.setDepartment(employ.getDepartmentName());
            attendanceRecordVO.setUserId(employ.getId());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            int year = calendar.get(Calendar.YEAR); //2024
            int month = calendar.get(Calendar.MONTH) + 1; // 月份从 0 开始计数，所以要加 1
            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // 获取当前月的第几天

            String formattedMonth = (month < 10) ? "0" + month : String.valueOf(month);
            String formattedDayOfMonth = (daysInMonth < 10) ? "0" + daysInMonth : String.valueOf(daysInMonth);
            String formattedTodayOfMonth = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth);
            int datate = year * 10000 + Integer.parseInt(formattedMonth) * 100 + Integer.parseInt(formattedDayOfMonth);//这个月的总天数
            int today = year * 10000 + Integer.parseInt(formattedMonth) * 100 + Integer.parseInt(formattedTodayOfMonth);//这个月的当天
            int thrMonth = year * 10000 + Integer.parseInt(formattedMonth) * 100 + 01; //这个月的第一天
            QueryWrapper<Attendancerecord> queryWrapper = new QueryWrapper<Attendancerecord>()
                    .select("department_id", "user_id", "adt_statu", "adt_in_time", "adt_out_time", "day", "adt_in_place", "adt_out_place", "update_time", "update_person", "remarks")
                    .eq("user_id", employ.getId())
                    .between("day",thrMonth,datate);
            List<Attendancerecord> attendancerecords = this.list(queryWrapper);
            attendanceRecordVO.setAttendancerecordList(attendancerecords);
            attendanceRecordVOList.add(attendanceRecordVO); // 将每个AttendanceRecordVO对象添加到列表中
        }
        System.out.println(attendanceRecordVOList);

        return attendanceRecordVOList;
    }
}
